//
//  CategorySettingViewController.m
//  SAYAKA_Table
//
//  Created by numanuma08 on 2013/07/20.
//  Copyright (c) 2013年 勘米良. All rights reserved.
//

#import "CategorySettingViewController.h"
#import "CategoryManager.h"
#import "Category.h"
#import "AppDelegate.h"

#define kCATEGORY_CELL @"CategoryCell"

@interface CategorySettingViewController ()
@property(strong, nonatomic) NSArray* categories;
@property(strong, nonatomic) NSDictionary* editButtons;
@property(strong, nonatomic) NSMutableArray* sortedHistory;
@end

@implementation CategorySettingViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
    NSManagedObjectContext* dbManager = appDelegate.managedObjectContext;
    _categories = [CategoryManager allRecord:dbManager];
    
    self.tabBarController.navigationItem.rightBarButtonItem = nil;
    UIBarButtonItem* editButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(selectSort:)];
    UIBarButtonItem* endEditButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(selectSortEnd:)];
    _editButtons = @{[NSNumber numberWithBool:YES]: endEditButton,
                     [NSNumber numberWithBool:NO]: editButton};
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    UIBarButtonItem* barButton = [_editButtons objectForKey:[NSNumber numberWithBool:self.tableView.isEditing]];
    self.tabBarController.navigationItem.rightBarButtonItem = barButton;
    
    _sortedHistory = [NSMutableArray array];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.navigationItem.rightBarButtonItem = nil;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSIndexPath* selectedRow = [self.tableView indexPathForSelectedRow];
    Category* selectedObject = [_categories objectAtIndex:selectedRow.row];
    
    UINavigationController* nextView = (UINavigationController*)segue.destinationViewController;
    CategoryEditViewController* destination = (CategoryEditViewController*)[nextView topViewController];
    destination.category = selectedObject;
    destination.parent = self;
}

- (IBAction)selectSort:(id)sender
{
    BOOL nowState = [self.tableView isEditing];
    [self.tableView setEditing:!nowState animated:YES];
    UIBarButtonItem* barButton = [_editButtons objectForKey:[NSNumber numberWithBool:!nowState]];
    self.tabBarController.navigationItem.rightBarButtonItem = barButton;
}

- (IBAction)selectSortEnd:(id)sender
{
    BOOL nowState = [self.tableView isEditing];
    [self.tableView setEditing:!nowState animated:YES];
    UIBarButtonItem* barButton = [_editButtons objectForKey:[NSNumber numberWithBool:!nowState]];
    self.tabBarController.navigationItem.rightBarButtonItem = barButton;

    
    [_sortedHistory enumerateObjectsUsingBlock:^(id object,NSUInteger index, BOOL* isStop){
        NSDictionary* sortedSet = (NSDictionary*)object;
        NSIndexPath* sourceIndexPath = (NSIndexPath*)[sortedSet objectForKey:@"source"];
        NSIndexPath* destinationIndexPath = (NSIndexPath*)[sortedSet objectForKey:@"destination"];
        
        Category* targetObject = [_categories objectAtIndex:sourceIndexPath.row];
        NSMutableArray* tempArray = [NSMutableArray arrayWithArray:_categories];
        [tempArray removeObjectAtIndex:sourceIndexPath.row];
        [tempArray insertObject:targetObject atIndex:destinationIndexPath.row];
        _categories = [NSArray arrayWithArray:tempArray];

        [_categories enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL* isStop){
            Category* category = (Category*)object;
            category.order_number = [NSNumber numberWithInteger:index];
        }];
    }];

    AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [delegate saveContext];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _categories.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCATEGORY_CELL];
    
    Category* category = [_categories objectAtIndex:indexPath.row];
    cell.textLabel.text = category.name;
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSDictionary* sortedSet = @{@"source": sourceIndexPath,
                                @"destination": destinationIndexPath};
    [_sortedHistory addObject:sortedSet];
}

-(NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    return proposedDestinationIndexPath;
}

# pragma mark - Category Edit View delegate
- (void)category:(Category *)category didCompleteEdit:(CategoryEditViewController *)viewController
{
    AppDelegate* appDeleaget = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDeleaget saveContext];
    
    NSManagedObjectContext* dbManager = appDeleaget.managedObjectContext;
    _categories = [CategoryManager allRecord:dbManager];
    [self.tableView reloadData];
}

- (void)didCancelEdit:(CategoryEditViewController *)viewController
{
    NSIndexPath* selectedPath = self.tableView.indexPathForSelectedRow;
    [self.tableView deselectRowAtIndexPath:selectedPath animated:YES];
}
@end
